package com.lej.core.utils.extention

import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.qmuiteam.qmui.kotlin.onClick
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * view执行协程
 * !!!注意:当view的context不是LifecycleOwner接口的Activity时,block代码将通过GlobalScope开启协程
 * */
fun View.scopeLaunch(
    cc: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
) : Job = (context as? LifecycleOwner)?.lifecycleScope?.launch(cc, start) { block() }
        ?: GlobalScope.launch(cc, start) { block() }

fun View.clickLaunch(
    cc: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
) {
    onClick {
        (context as? LifecycleOwner)?.lifecycleScope?.launch(cc, start) { block() }
            ?: GlobalScope.launch(cc, start) { block() }
    }
}

/**
 * view同步协程
 * !!!注意:当view的context不是LifecycleOwner接口的Activity时,block代码将通过GlobalScope开启协程
 * */
fun <T> View.scopeAsync(
    cc: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
    return (context as? LifecycleOwner)?.lifecycleScope?.async(cc, start) { block() }
        ?: GlobalScope.async(cc, start) { block() }
}